﻿using System;
using System.Configuration;

namespace Infrastructure.Common.Config.Imp
{
    public class AppConfig
    {
        /// <summary>
        ///     读取配置节，返回exe.config文件中Settings配置节中的value项
        /// </summary>
        /// <param name="strKey"></param>
        /// <returns></returns>
        public string GetAppConfig(string strKey)
        {
            return ConfigurationManager.AppSettings[strKey];
        }

        /// <summary>
        ///     xx.exe.config文件中appSettings配置节增加一对键、值对
        /// </summary>
        /// <param></param>
        /// <param></param>
        /// <param name="newKey"></param>
        /// <param name="newValue"></param>
        public void UpdateAppConfig(string newKey, string newValue)
        {
            bool isModified = false;
            foreach (string key in ConfigurationManager.AppSettings)
            {
                if (key == newKey)
                {
                    isModified = true;
                }
            }

            // 打开 App.Config 的可执行文件
            Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            // 您需要删除旧的设置对象才能取代它
            if (isModified)
            {
                config.AppSettings.Settings.Remove(newKey);
            }
            // 添加一个 Application Setting. 
            config.AppSettings.Settings.Add(newKey, newValue);
            // 保存更改 App.config 文件. 
            config.Save(ConfigurationSaveMode.Modified);
            // 强迫加载 
            ConfigurationManager.RefreshSection("appSettings");
        }

        public void Quote()
        {
            throw new NotImplementedException();
        }
    }
}